import 'dart:math';
import 'package:book_manager_app/app/modules/add_book/models/add_book_req.dart';
import 'package:book_manager_app/app/modules/add_book/models/book_package_info.dart';
import 'package:book_manager_app/app/modules/add_book/models/book_sales_req.dart';
import 'package:common_utils/common_utils.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:flutter/cupertino.dart';
import 'package:book_manager_app/app/modules/add_book/models/book.dart';
import 'package:book_manager_app/app/modules/add_book/request/book_request.dart';
import 'package:book_manager_app/app/utils/common/result_code.dart';
import 'package:book_manager_app/app/utils/widget/common.dart';
import 'package:get/get_connect/http/src/utils/utils.dart';
import 'package:sn_progress_dialog/sn_progress_dialog.dart';
import '../../../routes/app_pages.dart';
import '../../../utils/common/base_controller.dart';
import '../../add_book/models/tanshu_book_model.dart';
import '../request/home_request.dart';
import 'package:camera/camera.dart';
import 'package:mobile_scanner/mobile_scanner.dart';

class HomeController extends BaseController {

  // 待出售
  final bookSalesReqs = <BookSalesReq>[].obs;

  final List<String> list = [
    "开始统计",
  ];

  final buttonTitle = "开始统计".obs;
  double lightLevel = 0.0;

  @override
  onInit() {
    final random = Random();
    buttonTitle.value = list[random.nextInt(list.length)];
    // getLightLevel();
    super.onInit();
  }

  // getLightLevel() async {
  //   lightLevel = await ScannerView.startLightSensor();
  // }

  // /// 跳转到扫码界面
  // gotoScannerView() {
  //   // 随机修改按钮标题
  //   final random = Random();
  //   buttonTitle.value = list[random.nextInt(list.length)];
  //   // 跳转到扫码页面
  //   // Get.to(()=> ScannerView(callBack: scannerCallBack));

  // }

  void addBook(String barcode) {
    Get.toNamed(Routes.ADD_BOOK, arguments: barcode);
  }

  /// 扫码成功后的回调
  scannerCallBack(MobileScannerController scanner, name, barcode) async {
    if (barcode.isEmpty) { showMessage("条形码识别为空"); return; }
    if (name == "补货") addBook(barcode);
    if (name == "出售") addAwaitSaleBook(barcode); 
  }

  // 添加待出售图书
  addAwaitSaleBook(String barcode) async {
    if (bookSalesReqs.length > 10) {
      showMessage("待出库清单已满10本，请先出库!");
      return;
    }
    // 判断当前的码是否为套装二维码
    if (barcode.startsWith("book_package")) {
      // 获取套装信息
      await getPackageInfo(barcode.split("book_package_").last);
    }else {
      // 获取图书信息
      await getBookInfo(barcode);
    }
  }

  /// 获取图书的信息
  Future<void> getBookInfo(String isbn) async {
    showLoadingMessage("正在查询");
    final result = await BookRequest.getBookInfo(isbn);
    dismissLoading();
    if (result.success) {
      if (result.data is Map && result.data.containsKey("list")) {
        if (result.data['list'].isEmpty) {
          showAlertDialog(title: "请注意", message: "没有找到该图书");
        }
        final list = result.data['list'];
        final book = Book.fromJson(list.first);
        // 转换成出售请求参数
        final storeId = book.storeId.toString();
        final bookId = book.id.toString();
        final salePrice = book.discountPrice ?? book.salePrice ?? 0.0;
        final req = BookSalesReq(storeId: storeId, bookId: bookId, name: book.name, quantity: 1, payType: 3, salePrice: salePrice);
        // 添加到列表
        bookSalesReqs.add(req);
        // 刷新界面
        bookSalesReqs.refresh();
      }
    }else {
      showAlertDialog(title: "请注意", message: "没有找到该图书");
    }
  }


  /// 获取套装信息
  getPackageInfo(String barcode) async {
    showLoadingMessage("正在查询");
    final result = await BookRequest.getPackageInfo(barcode);
    dismissLoading();
    if (result.success) {
      final package = BookPackageInfo.fromJson(result.data);
      // 转换成出售请求参数
      final name = '${package.name}【套装】';
      final storeId = package.storeId.toString();
      final packageId = package.id.toString();
      final salePrice = package.originalTotalPrice ?? 0.0;
      final req = BookSalesReq(storeId: storeId, packageId: packageId, name: name, quantity: 1, payType: 1, salePrice: salePrice);
      // 添加到列表
      bookSalesReqs.add(req);
      // 刷新界面
      bookSalesReqs.refresh();
    }
  }


  /// 出售
sale() async {
  showAlertDialog(title: "确认付款", message: "请确认付款金额是否正确？", confirmText: "确认", confirm: () async {
      dismissAlertDialog();
      showLoadingMessage("出库中...");
      final sales = List<BookSalesReq>.from(bookSalesReqs);
      List<BookSalesReq> failedBooks = [];
      try {
        await Future.wait(
          sales.map((req) async {
            if (ObjectUtil.isNotEmpty(req.packageId)) {
              final result = await BookRequest.salePackage(req);
              if (!result.success) {
                failedBooks.add(req);
              }else {
                bookSalesReqs.remove(req);
                return result.success;
              }
            }else {
              final result = await BookRequest.sale(req);
              if (!result.success) {
                failedBooks.add(req);
              }else {
                bookSalesReqs.remove(req);
                return result.success;
              }
            }
          })
        );

        if (failedBooks.isEmpty) {
          showMessage("出库成功!");
          bookSalesReqs.clear(); // 出库成功，清空列表
        } else {
          bookSalesReqs.removeWhere((book) => !failedBooks.contains(book)); // 只保留失败项
          final failedNames = failedBooks.map((e) => e.name).join(", ");
          showAlertDialog(title: "请注意", message: "部分图书出库失败，请检查! $failedNames", confirmText: "重试", confirm: () {
            dismissAlertDialog();
            sale();
          });
        }
        bookSalesReqs.refresh();
      } catch (e) {
        debugPrint("出库过程中发生错误: $e");
        showMessage("出库过程中发生错误: $e");
      } finally {
        dismissLoading();
      }
  });
}


  /// 从探书添加图书
  Future<void> addBookFromTanshu(TanshuBook tanshuBook) async {
    final book = AddBookReq(
      isbn: tanshuBook.isbn,
      name: tanshuBook.title,
      imageUrl: tanshuBook.img,
      author: tanshuBook.author,
      publisher: tanshuBook.publisher,
      keyword: tanshuBook.keyword,
      referencePrice: double.tryParse(tanshuBook.price ?? "0"),
      purchasePrice: double.tryParse(tanshuBook.price ?? "0"),
      salePrice: double.tryParse(tanshuBook.price ?? "0"),
      discountPrice: double.tryParse(tanshuBook.price ?? "0"),
      inventory: 100,
    );
    final result = await BookRequest.addBook(book);
    if (result.success) {
      showMessage("添加成功");
    }else {
      showMessage("添加失败");
    }
  }
}
